package com.ahua.mallchat.common.common.event.listener;

import com.ahua.mallchat.common.adapter.WebSocketAdapter;
import com.ahua.mallchat.common.common.event.UserBlackEvent;
import com.ahua.mallchat.common.dao.UserDao;
import com.ahua.mallchat.common.domain.pojo.User;
import com.ahua.mallchat.common.service.WebSocketService;
import com.ahua.mallchat.common.service.cache.UserCache;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/**
 * 用户拉黑事件监听者
 */
@Component
public class UserBlackListener {

    @Resource
    private WebSocketService webSocketService;

    @Resource
    private UserDao userDao;

    @Resource
    private UserCache userCache;

    /**
     * 发送拉黑消息
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void sendMsg(UserBlackEvent event) {
        User user = event.getUser();
        webSocketService.sendMsgToAll(WebSocketAdapter.buildBlack(user));
    }

    /**
     * 修改用户状态
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void changeUserStatus(UserBlackEvent event) {
        userDao.invalidUid(event.getUser().getId());
    }

    /**
     * 清空缓存
     */
    @Async
    @TransactionalEventListener(classes = UserBlackEvent.class, phase = TransactionPhase.AFTER_COMMIT)
    public void evictCache(UserBlackEvent event) {
        userCache.evictBlackMap();
    }

}
